package com.bml.architect.springcloud.imports;

import org.springframework.context.annotation.DeferredImportSelector;
import org.springframework.core.Ordered;
import org.springframework.core.type.AnnotationMetadata;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class MyDefferImport implements DeferredImportSelector {
    @Override
    public String[] selectImports(AnnotationMetadata annotationMetadata) {

        return new String[0];
    }


    @Override
    public Class<? extends Group> getImportGroup() {
        return MyGroup.class;
    }

    static class ImportObject implements Ordered {
        private String importClassName;
        private int order;

        public ImportObject(String importClassName, AnnotationMetadata metadata, int order) {
            this.importClassName = importClassName;
            this.metadata = metadata;
            this.order = order;
        }

        private AnnotationMetadata metadata;

        public String getImportClassName() {
            return importClassName;
        }

        public void setImportClassName(String importClassName) {
            this.importClassName = importClassName;
        }

        public AnnotationMetadata getMetadata() {
            return metadata;
        }

        public void setMetadata(AnnotationMetadata metadata) {
            this.metadata = metadata;
        }

        @Override
        public int getOrder() {
            return order;
        }
    }


    static class MyGroup implements DeferredImportSelector.Group {

        final List<ImportObject> lists = new ArrayList<>();

        @Override
        public void process(AnnotationMetadata annotationMetadata, DeferredImportSelector deferredImportSelector) {
            lists.add(new ImportObject("com.bml.architect.springcloud.imports.AImport", annotationMetadata, 3));
            lists.add(new ImportObject("com.bml.architect.springcloud.imports.BImport", annotationMetadata, 2));


        }

        @Override
        public Iterable<Entry> selectImports() {
            //这里可以做排序
            List<Entry> collect = lists.stream().sorted(Comparator.comparing(ImportObject::getOrder))
                    .map(item -> new Entry(item.getMetadata(), item.getImportClassName())).collect(Collectors.toList());

            return collect;
        }
    }
}
